﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using C1Lib;

namespace FuturamaPDA {
	public class TagReader {
		private static TagReader instance;
		private Thread t;
		private Boolean isBusy;
		private Logger logger;
		public event EventHandler<ReadEventArgs> RfidScanned;
		public event EventHandler<ReaderErrorEventArgs> ReaderError;

		private TagReader() {
			this.isBusy = false;
			this.logger = Logger.Instance;
		}

		public static TagReader Instance {
			get {
				if (instance == null) {
					instance = new TagReader();
				}
				return instance;
			}
		}

		protected virtual void OnRfidScanned(ReadEventArgs e) {
			EventHandler<ReadEventArgs> handler = RfidScanned;
			if (handler != null) {
				handler(this, e);
			}
		}

		protected virtual void OnReaderError(ReaderErrorEventArgs e) {
			EventHandler<ReaderErrorEventArgs> handler = ReaderError;
			if (handler != null) {
				handler(this, e);
			}
		}

		private void read() {
			while (this.isBusy) {
				if (C1Lib.C1.NET_C1_open_comm() == 1 && C1Lib.C1.NET_C1_enable() == 1) {
					if (C1Lib.ISO_15693.NET_get_15693(0) != 0) {
						String tag_id = "";
						for (int i = 0; i < C1Lib.ISO_15693.tag.id_length; i++) {
							tag_id = tag_id + C1Lib.util.hex_value(C1Lib.ISO_15693.tag.tag_id[i]);
						}
						OnRfidScanned(new ReadEventArgs(tag_id));
						//Thread.Sleep(500);
					}
					//Thread.Sleep(600);
					Thread.Sleep(500);
				} else {
					//OnReaderError(new ReaderErrorEventArgs("De rfid reader is niet gevonden of werkt niet naar behoren."));
					//this.isBusy = false;
				}
			}
			C1Lib.C1.NET_C1_disable();
			C1Lib.C1.NET_C1_close_comm();
		}

		public void startReading() {
			if (this.isBusy == false) {
				this.isBusy = true;
				this.t = new Thread(new ThreadStart(read));
				this.t.Start();
			}
		}

		public void stopReading() {
			if (this.isBusy) {
				this.isBusy = false;
			}
		}

		public Boolean isReading() {
			return isBusy;
		}
	}

	public class ReadEventArgs : EventArgs {
		private String rfid;

		public ReadEventArgs(String rfid) {
			this.rfid = rfid;
		}

		public String Rfid {
			get { return this.rfid; }
		}
	}

	public class ReaderErrorEventArgs : EventArgs {
		private String errorMessage;

		public ReaderErrorEventArgs(String errorMessage) {
			this.errorMessage = errorMessage;
		}

		public String ErrorMessage {
			get { return this.errorMessage; }
		}
	}
}
